//
//  MyInfoViewController.m
//  Light
//
//  Created by 骁唐 on 15/9/7.
//  Copyright (c) 2015年 骁唐. All rights reserved.
//

#import "MyInfoViewController.h"
#import "UserInfoTableViewCell.h"
#import "constantDefinition.h"
#import "MBProgressHUD.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "UserConfig.h"
#import "UIImageView+WebCache.h"
#import "BloodTypeTableViewCell.h"
#import "LoginViewController.h"
#import "Header.h"
@interface MyInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UIPickerViewDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate,UIPickerViewDataSource, UIPickerViewDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backGround;

@property (strong,nonatomic) UIDatePicker *datePicker;
//第三方
@property (strong, nonatomic) IBOutlet UIView *pickerBgView;
@property (strong, nonatomic) IBOutlet UIPickerView *myPicker;
@property (strong, nonatomic) UIView *maskView;

@property (strong, nonatomic) NSDictionary *pickerDic;
@property (strong, nonatomic) NSArray *provinceArray;
@property (strong, nonatomic) NSArray *cityArray;
@property (strong, nonatomic) NSArray *townArray;
@property (strong, nonatomic) NSArray *selectedArray;

@end

@implementation MyInfoViewController
{
    UIAlertView *alert;
    NSString *fromCamera;
    UIImage *_headerImage;
    NSMutableDictionary *userInfoDic;
    NSArray *bloodArr;
    int changeIndex;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getPickerData];
    [self initView];
    //日期date
    _datePicker = [[UIDatePicker alloc] init];
    _datePicker.datePickerMode = UIDatePickerModeDate;
    _datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"Chinese"];
    CGRect frame = _datePicker.frame;
    //frame.origin = CGPointMake(0,0);
    _datePicker.frame = frame;
    _datePicker.hidden = YES;
    [self.datePickerView addSubview:_datePicker];
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    MBProgressHUD *progressView = [[MBProgressHUD alloc]initWithView:self.view];
    progressView.delegate       = self;
    progressView.labelText      = @"";
    self.mbProgressHud       = progressView;
    [self.view addSubview:progressView];
    userInfoDic = [[NSMutableDictionary alloc]init];
    
    [_bloodView.layer setMasksToBounds:YES];
    [_bloodView.layer setCornerRadius:7.0];
    
//    [self regNotification];
    
    //获取编辑完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeComplete:) name:@"change" object:nil];
    //开始编辑的行
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeStart:) name:@"changeIndex" object:nil];
    
    bloodArr = @[@"O型",@"A型",@"B型",@"AB型",@"其他"];
}

#pragma mark -
#pragma mark 跟新数据
- (void)changeComplete:(NSNotification *)note {
    
    switch ([note.userInfo[@"indexPath"] intValue]) {
        case 100:
            userInfoDic[@"name"] = note.userInfo[@"text"];
            break;
        case 300:
            userInfoDic[@"birthday"] = note.userInfo[@"text"];
            break;
        case 400:
            userInfoDic[@"humanHeight"] = note.userInfo[@"text"];
            break;
        case 500:
            userInfoDic[@"weight"] = note.userInfo[@"text"];
            break;
        case 700://地区
            userInfoDic[@"region"] = note.userInfo[@"text"];
            break;
        case 800://详细地址（用的病历的字段）
            userInfoDic[@"medicalhistory"] = note.userInfo[@"text"];
            break;
        default:
            break;
    }
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return  YES;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldBeRequiredToFailByGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return [gestureRecognizer isKindOfClass:UIScreenEdgePanGestureRecognizer.class];
}

- (void)changeStart :(NSNotification *)note{
    
    changeIndex = [note.userInfo[@"indexPath"] intValue];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {
    [self getUserInfo];//网络获取用户信息，需要做本地缓存的
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _bloodTypeTableView) {
        return bloodArr.count;
    }
    return 9;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == _bloodTypeTableView) {
        return 55;
    }else {
        if (indexPath.row == 0) {
            return 100;
        }
        return 55;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentify = @"userinfoCell";
    static NSString *cellBlood = @"bloodTypeCell";
    if (tableView == _userInfoTableView)
    {
        UserInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.cellResultTextField.tag = 100*indexPath.row;
        switch (indexPath.row)
        {
            case 0:
            {
                cell.cellHeadImage.hidden = NO;
                if (_headerImage == nil) {
                      NSURL *imageUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",PICTURE_HEAD,userInfoDic[@"image"]]];
                    [cell.cellHeadImage sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:@"user - head"]];
                }
                else
                {
                    [cell.cellHeadImage setImage:_headerImage];
                }
                cell.cellTitleLabel.hidden = NO;
                cell.cellResultTextField.hidden = YES;
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                
                cell.arrowRight.hidden = NO;//右箭头(TODO:箭头颜色是灰色的)
                cell.arrowRight.alpha = 0.5;
            }
                break;
            case 1:
            {
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = YES;//右箭头
                cell.cellTitleLabel.text = @"名字";
                cell.cellResultTextField.text = userInfoDic[@"name"];
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.enabled = YES;
                cell.cellResultTextField.keyboardType = UIKeyboardTypeDefault;//设置键盘格式
            }
                break;
            case 2:
            {
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = YES; //内容
                cell.manImage.hidden = NO;
                cell.manBut.hidden = NO;
                cell.manLabel.hidden = NO;
                cell.womanBut.hidden = NO;
                cell.womanImage.hidden = NO;
                cell.womanLabel.hidden = NO;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = YES;//右箭头
                
                //男女性别展示
                cell.cellTitleLabel.text = @"性别";
                if ([userInfoDic[@"gender"] isEqualToString:@"男"]) {
                    
                    [cell.manImage setImage:[UIImage imageNamed:@"man"]];
                    [cell.womanImage setImage:[UIImage imageNamed:@"woman"]];
                    
                }else if ([userInfoDic[@"gender"] isEqualToString:@"女"]) {
                    
                    [cell.manImage setImage:[UIImage imageNamed:@"man_2"]];
                    [cell.womanImage setImage:[UIImage imageNamed:@"woman_2"]];
                    
                }
                //男女性别选择
                [cell setButtonAction:^(ButtonType type, UserInfoTableViewCell *cell) {
                    if (type == manButton) {
                        [cell.manImage setImage:[UIImage imageNamed:@"man"]];
                        [cell.womanImage setImage:[UIImage imageNamed:@"woman"]];
                        userInfoDic[@"gender"] = @"男";
                    }else if (type == womanButton) {
                        [cell.manImage setImage:[UIImage imageNamed:@"man_2"]];
                        [cell.womanImage setImage:[UIImage imageNamed:@"woman_2"]];
                        userInfoDic[@"gender"] = @"女";
                    }
                }];
//                cell.manImage.hidden = NO;
//                cell.womanImage.hidden = NO;
//                cell.manLabel.hidden = NO;
//                cell.womanLabel.hidden = NO;
//                cell.arrowRight.hidden = YES;//右箭头
            }
                break;
            case 3:
            {//出身日期
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = NO;//右箭头
                
                cell.cellTitleLabel.text = @"出生日期";
                cell.cellResultTextField.textColor  = APPCOLOUR;
                cell.cellResultTextField.enabled = NO;//不可编辑
                NSString *birthday = userInfoDic[@"birthday"];
                
                if (birthday.length > 10)
                {
                    NSString * stringBirthDay = [birthday substringWithRange:NSMakeRange(0, 10)];
                    cell.cellResultTextField.text = stringBirthDay;
                    
                    //获取用户的出生日期，然后转换格式，datePicker设置
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
                    NSDate * date  = [NSDate date];
                    if (stringBirthDay.length != 0) {
                        date=[dateFormatter dateFromString:stringBirthDay];
                    }
                    [self.datePicker setDate:date];

                }
                else
                {
                    cell.cellResultTextField.text = birthday;
                }
//                cell.arrowRight.hidden = NO;//右箭头
            }
                break;
            case 4:
            {//身高
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = YES;//右箭头
                
                cell.cellTitleLabel.text = @"身高（cm）";
                cell.cellResultTextField.enabled = YES;//可编辑
                cell.cellResultTextField.text = [NSString stringWithFormat:@"%@",userInfoDic[@"humanHeight"]] ;
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.keyboardType = UIKeyboardTypeNumberPad;//设置键盘格式
//                cell.arrowRight.hidden = YES;//右箭头
            }
                break;
            case 5:
            {//体重
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = YES;//右箭头
                
                cell.cellTitleLabel.text = @"体重（kg）";
                cell.cellResultTextField.enabled = YES;//可编辑
                cell.cellResultTextField.text = [NSString stringWithFormat:@"%@",userInfoDic[@"weight"]];
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.keyboardType = UIKeyboardTypeNumberPad;//设置键盘格式
//                cell.arrowRight.hidden = YES;//右箭头
            }
                break;
            case 6:
            {//血型
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = NO;//右箭头
                cell.cellTitleLabel.text = @"选择血型";
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.enabled = NO;//不可编辑
                cell.cellResultTextField.text = userInfoDic[@"bloodType"];
//                cell.arrowRight.hidden = NO;//右箭头
            }
                break;
            case 7:
            {//城市
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = NO;//右箭头
                cell.cellTitleLabel.text = @"城市";
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.text = userInfoDic[@"region"];
                cell.cellResultTextField.enabled = NO;//不可编辑
            }
                break;
            case 8:
            {//详细地址
                cell.cellTitleLabel.hidden = NO;//title
                cell.cellResultTextField.hidden = NO; //内容
                cell.manImage.hidden = YES;
                cell.manBut.hidden = YES;
                cell.manLabel.hidden = YES;
                cell.womanBut.hidden = YES;
                cell.womanImage.hidden = YES;
                cell.womanLabel.hidden = YES;
                cell.cellHeadImage.hidden = YES;//头像
                cell.arrowRight.hidden = YES;//右箭头
                cell.cellTitleLabel.text = @"详细地址";
                cell.cellResultTextField.textColor = APPCOLOUR;
                cell.cellResultTextField.text = userInfoDic[@"medicalhistory"];
                cell.cellResultTextField.enabled = YES;//可编辑
                cell.cellResultTextField.keyboardType = UIKeyboardTypeDefault;//设置键盘格式
//                cell.cellResultTextField.frame = CGRectMake(CGRectGetMaxX(cell.cellTitleLabel.frame), cell.cellResultTextField.frame.origin.y, SCREEN_WIDTH-10, cell.cellResultTextField.frame.size.height);
//                cell.arrowRight.hidden = YES;//右箭头
            }
                break;
            default:
                break;
        }
        return cell;
    }
    else if (tableView == _bloodTypeTableView)
    {
        BloodTypeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellBlood];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.bloodTypeLabel.text = bloodArr[indexPath.row];
        return cell;
    }
    return nil;
}

#pragma mark -
#pragma mark 点击选择具体的cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self performSelector:@selector(dissmissSelectCell) withObject:self afterDelay:0.1];
//    UITextField *textField = (UITextField *)[self.view viewWithTag:100*indexPath.row];
    
//    //第一响应者
//    [textField becomeFirstResponder];
//    if (indexPath.row == 7)
//    {//城市选择
//        [textField resignFirstResponder];
//    }
    
    if (tableView == _bloodTypeTableView)
    {//如果是血液选择tableView
        userInfoDic[@"bloodType"] = bloodArr[indexPath.row];//存储选择的血液
        _holdBloodView.hidden = YES;//隐藏血液选择tableView
        [_userInfoTableView reloadData];//刷新用户信息
    }
    else if (tableView == _userInfoTableView)
    {//如果是用户tableView
        switch (indexPath.row)
        {
            case 0:
            {//头像
                UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                              initWithTitle:@"请选择一张图片"
                                              delegate:self
                                              cancelButtonTitle:@"取消"
                                              destructiveButtonTitle:nil
                                              otherButtonTitles:@"拍照", @"相册", nil];
                [actionSheet showInView:self.view];
            }
                break;
            case 2:
            {//性别 直接选择按钮的。按钮打开就行，这边不做操作。
            }
                break;
            case 3:
            {//出身日期
                self.holdBloodView.hidden = NO;//不能隐藏，都是加载在这个view上的。
                self.bloodView.hidden = YES;
                self.datePicker.hidden = NO;
                self.datePickerView.hidden = NO;
            }
                break;
            case 4: //身高
            case 5: //体重
            case 1: //姓名
            case 8: //详细地址
            {
                UITextField *textField = (UITextField *)[self.view viewWithTag:100*indexPath.row];
                if (indexPath.row ==4 || indexPath.row == 5)
                {//设置键盘弹出类型
                    textField.keyboardType = UIKeyboardTypeNumberPad;
                }
                else
                {
                    textField.keyboardType = UIKeyboardTypeDefault;
                }
                [textField becomeFirstResponder];//第一响应者

            }
                break;
            case 6:
            {//选择血型
                _holdBloodView.hidden = NO;
                self.bloodView.hidden = NO;
                self.datePickerView.hidden = YES;
            }
                break;
            case 7:
            {//城市选择
                [self.view addSubview:self.maskView];
                [self.view addSubview:self.pickerBgView];
                self.maskView.alpha = 0;
                self.pickerBgView.top = self.view.height;
                [UIView animateWithDuration:0.3 animations:^{
                    self.maskView.alpha = 0.3;
                    self.pickerBgView.bottom = self.view.height;
                }];
            }
                break;
            default:
                break;
        }
    }
}

#pragma mark -
#pragma mark dissmissSelectCell
- (void)dissmissSelectCell {
    [_userInfoTableView deselectRowAtIndexPath:[_userInfoTableView indexPathForSelectedRow] animated:YES];
}

#pragma mark - ActionSheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            [self takePhotoByCamera];
            fromCamera = @"camera";
            break;
        case 1:
            [self takePhotoByPhotoLibrary];
            fromCamera = @"library";
        default:
            break;
    }
    
}
#pragma mark - ImagePicker相关
#pragma mark 照相机
- (void)takePhotoByCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.allowsEditing = NO;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 相册
- (void)takePhotoByPhotoLibrary {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = NO;
    picker.delegate = self;
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark -
#pragma mark 选择图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:
(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    _headerImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //如果是拍照则保存到相册
//    if ([fromCamera isEqualToString:@"camera"]) {
//        
//        UIImageWriteToSavedPhotosAlbum(_headerImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
//    }
    CGSize imagesize = _headerImage.size;
    imagesize.height =500;
    imagesize.width =400;
    //对图片大小进行压缩--
    _headerImage = [self imageWithImage:_headerImage scaledToSize:imagesize];
    [_userInfoTableView reloadData];
    [self updataUserImage];
    // haveChangeImage = @"haveChange";
}

#pragma mark -
#pragma mark 获取用户信息
- (void)getUserInfo {
    [_mbProgressHud show:YES];
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    NSDictionary *dic = @{@"Token":[userConfig getToken]};
    //地址
    [httpManager POST:GET_INFO parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"获取成功");
                  //处理后台返回空字段
                  NSMutableString *string = [NSMutableString stringWithString:dic[@"b"]];
                  [string replaceOccurrencesOfString:@"null" withString:@"\"\"" options:NSLiteralSearch range:NSMakeRange(0, string.length)];
                  
                  NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:string];
                  
                  if ([dic[@"a"] intValue] == 1) {
                      
                      userInfoDic = [resDic mutableCopy];
                      
                      [_userInfoTableView reloadData];
                      
                  }else if ([dic[@"a"] intValue] == -1) {
                      [self loginOut];//登录失效
                  }else if ([dic[@"a"] intValue] == 0) {
                      
                      ALERT_VIEW(@"获取失败");
                  }
                  _mbProgressHud.hidden = YES;
                  
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"信息获取失败");
                  _headerImage = [UIImage imageNamed:@"user - head"];
                  _mbProgressHud.hidden = YES;
                  [_userInfoTableView reloadData];
              }];
}

#pragma mark -
#pragma mark 登录过期
- (void)loginOut
{
    if (TJJiOS8)
    {
        UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:Alertview animated:YES completion:nil];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }];
        
        [Alertview addAction:action];
    }
    else
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
        alertView.tag = 97;
        [alertView show];
    }
}

#pragma mark -
#pragma mark 上传头像
- (void)updataUserImage {
    NSData *imageData;
    if (UIImagePNGRepresentation(_headerImage) == nil) {
        imageData = UIImageJPEGRepresentation(_headerImage, 1);
    } else {
        imageData = UIImagePNGRepresentation(_headerImage);
    }
    //base64位编码
    NSString *base64Str = [imageData base64EncodedStringWithOptions:0];
    
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    //上传图片
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    NSDictionary *dic = @{@"Token":[userConfig getToken],@"image":base64Str};
    //地址
    [httpManager POST:USER_HEADIMAGE parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"上传成功");
                  if ([retDic[@"a"] intValue] == 1) {
                      
                      UserConfig *userConfig = [UserConfig sharingUserConfig];
                      [userConfig setUserHeadData:imageData];
                      [userConfig setcurrentHeadImage:retDic[@"b"]];
                      
                      
                  }else if ([retDic[@"a"] intValue] == -1) {
                      [self loginOut];//登录失效
                  }else if ([retDic[@"a"] intValue] == 0) {
                      ALERT_VIEW(@"修改失败");
                  }
                  
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"上传失败");
                  _headerImage = [UIImage imageNamed:@"user - head"];
              }];
}

#pragma mark -
#pragma mark  网络更新用户数据请求
- (void)updataUserInfo {
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[userConfig getToken] forKey:@"Token"];//提交Token
    if ([TJJDefines isNull:userInfoDic[@"humanHeight"]])
    {//如果该字段为空
        [dic setObject:@"65" forKey:@"humanHeight"];//提交体重
    }
    else
    {
        [dic setObject:userInfoDic[@"humanHeight"] forKey:@"humanHeight"];//提交体重
    }
    
    [dic setObject:userInfoDic[@"grade"] forKey:@"grade"];//提交等级
    [dic setObject:userInfoDic[@"age"] forKey:@"age"];//提交年龄
    [dic setObject:userInfoDic[@"medicalhistory"] forKey:@"medicalhistory"];//详细地址
    [dic setObject:userInfoDic[@"region"] forKey:@"region"];//地区
    [dic setObject:userInfoDic[@"gender"] forKey:@"gender"];//提交性别
    [dic setObject:userInfoDic[@"name"] forKey:@"name"];//提交昵称
    [dic setObject:userInfoDic[@"birthday"] forKey:@"birthday"];//提交生日
    [dic setObject:userInfoDic[@"weight"] forKey:@"weight"];//提交体重
    [dic setObject:userInfoDic[@"bloodType"] forKey:@"bloodType"];//提交血型
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    [httpManager POST:SET_INFO parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *retDic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"上传成功");
                  
                  if ([retDic[@"a"] intValue] == 1) {
                      [userConfig setCurrentBirthday:userInfoDic[@"birthday"]];//保存生日
                      [userConfig setCurrentHeight:userInfoDic[@"humanHeight"]];//保存身高
                      [userConfig setCurrentWeight:userInfoDic[@"weight"]];//保存体重
                      [userConfig setCurrentuserGender:userInfoDic[@"gender"]];//保存性别
                      [userConfig setCurrentNickName:userInfoDic[@"name"]];//保存昵称
                      //如果用户等级为空，需要初始化为1
                      if ([userInfoDic[@"grade"] intValue] > 0)
                      {
                          [userConfig setcurrentLevel:userInfoDic[@"grade"]];//保存用户等级
                      }
                      else
                      {
                          [userConfig setcurrentLevel:@"0"];//保存用户等级 0
                      }
                      [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationUpdataUserInfo" object:nil];//通知 更新个人信息(User界面)
                  }
                  else if ([retDic[@"a"] intValue] == -1)
                  {
                      [self loginOut];//登录失效
                  }
                  else if ([retDic[@"a"] intValue] == 0)
                  {
                      ALERT_VIEW(retDic[@"b"]);
                  }
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"上传失败");
              }];
}

#pragma mark -
#pragma mark 图片剪切
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

#pragma mark -
#pragma mark 导航返回
- (IBAction)backClick {
    // NSLog(@"%@",userInfoDic);
    [self.navigationController popViewControllerAnimated:YES];
    [self updataUserInfo];
}

#pragma mark -
#pragma mark 点击空白处，生日滚轮回收，存成用户生日
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    self.holdBloodView.hidden = YES;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:self.datePicker.date];
    NSLog(@"%@", strDate);
    userInfoDic[@"birthday"] = strDate;
    [_userInfoTableView reloadData];
}
//#pragma mark - reg & unreg notification
//- (void)regNotification
//{
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
//}
//
//- (void)unregNotification
//{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
//}
//
//#pragma mark - notification handler
//
//- (void)keyboardWillChangeFrame:(NSNotification *)notification
//{
//    NSDictionary *info = [notification userInfo];
//    // CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
//    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
//    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
//    
//    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
//    NSLog(@"===============%f",yOffset);
//    if (changeIndex == 700 || changeIndex == 800 ) {
//        [UIView animateWithDuration:0.3 animations:^{
//            _tableViewTop.constant += yOffset;
//            _tableViewBottom.constant -= yOffset;
//        }];
//    }
//}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

#pragma mark - init view
- (void)initView {
    self.maskView = [[UIView alloc] initWithFrame:kScreen_Frame];
    self.maskView.backgroundColor = [UIColor blackColor];
    self.maskView.alpha = 0;
    [self.maskView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideMyPicker)]];
    
    self.pickerBgView.width = kScreen_Width;
}

#pragma mark - get data
- (void)getPickerData {
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    self.pickerDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.provinceArray = [self.pickerDic allKeys];
    self.selectedArray = [self.pickerDic objectForKey:[[self.pickerDic allKeys] objectAtIndex:0]];
    
    if (self.selectedArray.count > 0) {
        self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
    }
    
    if (self.cityArray.count > 0) {
        self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
    }
    
}

#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    } else {
        return self.townArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row];
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row];
    } else {
        return [self.townArray objectAtIndex:row];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return 110;
    } else if (component == 1) {
        return 100;
    } else {
        return 110;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:row]];
        if (self.selectedArray.count > 0) {
            self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
        } else {
            self.cityArray = nil;
        }
        if (self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
        } else {
            self.townArray = nil;
        }
    }
    [pickerView selectedRowInComponent:1];
    [pickerView reloadComponent:1];
    [pickerView selectedRowInComponent:2];
    
    if (component == 1) {
        if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:row]];
        } else {
            self.townArray = nil;
        }
        [pickerView selectRow:1 inComponent:2 animated:YES];
    }
    
    [pickerView reloadComponent:2];
}

#pragma mark - private method

//取消
- (IBAction)cancel:(id)sender {
    [self hideMyPicker];
}
//确定
- (IBAction)ensure:(id)sender {
    NSString *currentName = [[NSString alloc] initWithFormat:@"%@%@%@",[self.provinceArray objectAtIndex:[self.myPicker selectedRowInComponent:0]],[self.cityArray objectAtIndex:[self.myPicker selectedRowInComponent:1]],[self.townArray objectAtIndex:[self.myPicker selectedRowInComponent:2]]];
    userInfoDic[@"region"] = currentName;
    [_userInfoTableView reloadData];
    NSLog(@"%@",currentName);
    [self hideMyPicker];
}

- (void)hideMyPicker {
    [UIView animateWithDuration:0.3 animations:^{
        self.maskView.alpha = 0;
        self.pickerBgView.top = self.view.height;
    } completion:^(BOOL finished) {
        [self.maskView removeFromSuperview];
        [self.pickerBgView removeFromSuperview];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 97:
        {//重新登录
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        default:
            break;
    }
}
@end
